/**   
 * 文件名: SMSUtils.java 
 * 包名：com.zlinepay.payment.ac.util 
 * 版权： 成都中联信通科技有限公司
 * 描述: 发送短信
 * 版本： V1.0 
 * 修改人：
 * 修改时间：
 * 修改内容：  
 */
package com.cms.support;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class SMSUtils {
	public static final Logger LOGGER = Logger.getLogger(SMSUtils.class);
	/** 畅卓参数 */
	public final static String SMS_CZ_URL = PropertyUtil.getValue("property",
			"SMS_CZ_URL", null);
	public final static String SMS_CZ_ACCOUNT = PropertyUtil.getValue("property",
			"SMS_CZ_ACCOUNT", null);
	public final static String SMS_CZ_PWD = PropertyUtil.getValue("property",
			"SMS_CZ_PWD", null);
	public final static String SMS_CZ_USERID = PropertyUtil.getValue("property",
			"SMS_CZ_USERID", null);
	/** 美联参数 */
	public final static String SMS_ML_URL = PropertyUtil.getValue("property",
			"SMS_ML_URL", null);
	public final static String SMS_ML_ACCOUNT = PropertyUtil.getValue("property",
			"SMS_ML_ACCOUNT", null);
	public final static String SMS_ML_PWD = PropertyUtil.getValue("property",
			"SMS_ML_PWD", null);
	public final static String SMS_ML_APIKEY = PropertyUtil.getValue(
			"property", "SMS_ML_APIKEY", null);
	public final static String SMS_ML_OVERAGE = PropertyUtil.getValue(
			"property", "SMS_ML_OVERAGE", null);

	/** 成功码 */
	public final static String SUCCESS_CODE = "0";
	public final static String PHONE = "PHONE";
	public final static String SMS = "SMS";
	public final static String EXT = "EXT";

	public static void main(String[] args) throws Exception {
		System.out.println(SMSUtils.sendByML("15928165825",
				"验证码5986,您的银行卡尾号2368付款金额3.56元，请确认为本人交易，切勿泄漏验证码。【中联信通】"));
	}

	/**
	 * 发送短信
	 * 
	 * @param phone
	 *            电话号码
	 * @param msg
	 *            短信内容
	 * @param actionInvoker
	 *            发送方（决定短信通道） ，参见CodeConstant.ACTION_INVOKER
	 * @return
	 * @throws CoreException
	 */
	public static Result sendSMS(String phone, String msg) throws Exception {
		return sendByML(phone, msg);
	}

	public static Result sendByCZ(String phone, String msg) {
		Result backResult = new Result();
		try {
			// action=send&account=账号&password=密码&mobile=手机号&content=内容&sendTime=
			// 发送POST请求
			String postData = "action=send&account=" + SMS_CZ_ACCOUNT
					+ "&password=" + SMS_CZ_PWD + "&mobile=" + phone
					+ "&content=" + msg + "&sendTime=";
			URL url = new URL(SMS_CZ_URL);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setUseCaches(false);
			conn.setDoOutput(true);

			conn.setRequestProperty("Content-Length", "" + postData.length());
			OutputStreamWriter out = new OutputStreamWriter(
					conn.getOutputStream(), "UTF-8");
			out.write(postData);
			out.flush();
			out.close();

			// 获取响应状态
			if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
				return new Result(false, "连接短信通道失败");
			}
			// 获取响应内容体
			String line, result = "";
			BufferedReader in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), "utf-8"));
			while ((line = in.readLine()) != null) {
				result += line + "\n";
			}
			in.close();

			try {
				Document doc = DocumentHelper.parseText(result);
				Element root = doc.getRootElement();
				System.out.println(root.getName());
				@SuppressWarnings("unchecked")
				Iterator<Element> iterator = root.elementIterator();

				while (iterator.hasNext()) {
					Element element = iterator.next();
					if ("returnstatus".equals(element.getName())) {
						if ("Faild".equals(element.getText())) {
							backResult.setSuccess(false);
						} else {
							backResult.setSuccess(true);
						}
					}
					if ("message".equals(element.getName())) {
						backResult.setObj(element.getText());
					}
				}
			} catch (DocumentException e) {
				e.printStackTrace();
			}
			return backResult;
		} catch (IOException e) {
			e.printStackTrace();
			backResult.setSuccess(false);
			backResult.setObj("系统异常" + e.getMessage());
			return backResult;
		}
	}

	/**
	 * 美联通道发送短信
	 * 
	 * @param phone
	 * @param msg
	 * @return
	 */
	public static Result sendByML(String phone, String msg) {
		Result backResult = new Result();
		try {
			String postData = "username=" + SMS_ML_ACCOUNT + "&password="
					+ SMS_ML_PWD + "&apikey=" + SMS_ML_APIKEY + "&mobile="
					+ phone + "&content=" + msg;
			URL url = new URL(SMS_ML_URL);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setUseCaches(false);
			conn.setDoOutput(true);

			conn.setRequestProperty("Content-Length", "" + postData.length());
			OutputStreamWriter out = new OutputStreamWriter(
					conn.getOutputStream(), "UTF-8");
			out.write(postData);
			out.flush();
			out.close();

			// 获取响应状态
			if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
				return new Result(false, "连接短信通道失败");
			}
			// 获取响应内容体
			String line, result = "";
			BufferedReader in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), "utf-8"));
			while ((line = in.readLine()) != null) {
				result += line + "\n";
			}
			in.close();
			if (result != null && result.contains("error")) {
				backResult.setSuccess(false);
			}
			backResult.setObj(result);
			return backResult;
		} catch (IOException e) {
			e.printStackTrace();
			backResult.setSuccess(false);
			backResult.setObj("系统异常" + e.getMessage());
			return backResult;
		}
	}
}
